<?php


namespace app\erp\controller;


use app\admin\controller\Base;
use app\admin\model\Admin;
use app\common\model\Users as UsersModel;
use app\common\model\UsersAddress as UsersAddressModel;
use app\common\widget\Widget;
use think\facade\Env;
//用户地址列表
class UsersAddress extends Base
{


    function index(){

        //---筛选

        //查询：时间格式过滤 获取格式 2015-11-12 - 2015-11-18
        $sldate = input('reservation', '');
        $arr    = explode(" - ", $sldate);
        $map    = [

        ];
        $map[]=['uid','=',input('uid')];
        if (count($arr) == 2) {
            $arrdateone = strtotime($arr[0]);
            $arrdatetwo = strtotime($arr[1] . ' 23:59:59');
            $map[]      = ['a.create_time', 'between', [$arrdateone, $arrdatetwo]];
        }
        //---时间格式

        if (input('mobile', '')!=''){
            $map[] = ['a.mobile', 'like', "%" . input('mobile') . "%"];
        }
        if (input('realname', '')!=''){
            $map[] = ['a.realname', 'like', "%" .  input('realname') . "%"];
        }
        if (input('user_type', '')!=''){
            $map[] = ['a.user_type', '=', input('user_type') ];
        }
        //---筛选结束


        //        每页多少条
        $list_rows=input('list_rows', '');
        if ($list_rows==''){
            $list_rows=config('paginate.list_rows');
        }


        $model = new UsersAddressModel();
        $news       = $model->alias("a")
//            ->field('a.*,b.realname as b_realname,c.realname as c_realname')
              //  ->with(['followId','sellId'])
//            ->join( 'users b', 'a.follow_id =b.id')
//            ->join( 'users c', 'a.sell_id =c.id')
            ->where($map)
            ->order('a.default asc')
            //->select();

            ->paginate($list_rows, false, ['query' => get_query()]);


        $page       = $news->render();
        $page       = preg_replace("(<a[^>]*page[=|/](\d+).+?>(.+?)<\/a>)", "<a href='javascript:ajax_page($1);'>$2</a>", $page);
        $data       = $news->items();

        //序号/姓名/头像/手机号/客户类型/状态/来源/归属/购买次数/总金额（元）/余额（元）/收货地址/创建时间/操作
        //表格字段
        $fields = [
            ['title' => 'ID/序号', 'field' => 'id'],
            ['title' => '用户id', 'field' => 'uid'],
            ['title' => '收货人姓名', 'field' => 'name'],
            ['title' => '手机号', 'field' => 'mobile'],
            ['title' => '省', 'field' => 'province_text'],
            ['title' => '市', 'field' => 'city_text'],
            ['title' => '县', 'field' => 'district_text'],
            ['title' => '详细地址', 'field' => 'address'],
            ['title' => '是否默认', 'field' => 'default', 'type' => 'array', 'array' =>$model->default_text ],

//            ['title' => '创建时间', 'field' => 'reg_time']
//            ['title' => '创建时间', 'field' => 'reg_time', 'type' => 'date']
        ];
        $pk     = 'id';
        //右侧操作按钮
        $right_action = [];
        $order        = url('newsOrder');
        $delall       = url('newsAlldel');
        $search       = [
        ];
        if (!config('yfcmf.lang_switch_on')) {
            unset($search[2]);
        }
        $form         = [
            'href'  => url('newsIndex'),
            'class' => 'form-search',
            'id'    => 'list-filter'
        ];
        //实例化表单类
        $widget = new Widget();
        if (request()->isAjax()) {
            return $widget
                ->form('table', $fields, $pk, $data, $right_action, $page, $order, $delall, 1);
        } else {
            return $widget
                ->addToparea(['add' => ['href' => url('add'), 'is_pop' => 1]], [], $search, $form)
//                ->setTemplate(Env::get('app_path') . 'common/widget/form/layout.html')

                ->addtable($fields, $pk, $data, $right_action, $page, $order, $delall)
                ->setButton()
                ->fetch();

        }
    }

    /**
     * 添加显示
     * @throws
     */
    public function add()
    {

       $AdminModel=new Admin;
       $UsersAddressModel= new UsersAddressModel();
      // dump($AdminModel->get_admin_name(3));die;
        //实例化表单类
        $widget = new Widget();
        return $widget
//单行文本输入 addText，下拉框 addSelect，多选框 addCheckbox，单图上传 addImage，多图上传 addImages，
//开关 addSwitch，时间 addDate，多行文本框 addTextarea，富文本 addUeditor

            ->addImage('photo', '头像上传', '', '上传前先用PS处理成等比例图片后上传，最后都统一比例')
            ->addSelect('follow_id', '开发', $AdminModel->get_admin_name(4), '','','', ['default' => '选择开发'])
            ->addSelect('sell_id', '销售', $AdminModel->get_admin_name(3), '','','', ['default' => '选择销售'])

            ->addText('mobile', '手机号', '', '', 'required', 'text',['placeholder' => '必填'])
            ->addText('realname', '姓名', '', '', 'required', 'text',['placeholder' => '必填'])
            ->addSelect('user_type', '类型', $UsersAddressModel->user_type_text, '1','','')
            ->addSelect('status', '状态', $UsersAddressModel->lock_trxt, '1','','' )
            ->addSelect('come_from', '来源', $UsersAddressModel->come_from_text, '2','','' )
            ->addTextarea('address', '文章简介', '', '已限制在100个字以内', '', ['maxlength' => 100, 'autosize' => 1])

            ->setUrl(url('addSave'))
            ->setAjax('ajaxForm-noJump')
            ->fetch();
    }

    /**
     * 增加
     */
    public function addSave()
    {

        $add_data  =input('');

        $rst             = UsersAddressModel::create($add_data);
        if ($rst) {
            $this->success('添加成功,返回列表页', 'index', ['is_frame' => 1]);
        } else {
            $this->error('添加失败,返回列表页', 'index', ['is_frame' => 1]);
        }
    }

    /**
     * 编辑显示
     * @throws
     */
    public function edit()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数错误', 'index');
        }
        $list    = XJihua::get($id);
        //实例化表单类
        $widget = new Widget();
        return $widget
//单行文本输入 addText，下拉框 addSelect，多选框 addCheckbox，单图上传 addImage，多图上传 addImages，
//开关 addSwitch，时间 addDate，多行文本框 addTextarea，富文本 addUeditor， 设置触发 setTrigger
            ->addText('id', '', $id, '', '', 'hidden')
            ->addText('username', '用户账户/手机号', $list['username'], '', 'required', 'text',['placeholder' => '必填'])
            ->addText('password', '登陆密码', '', '', 'required', 'text',['placeholder' => '不修改请放空'])
            ->addText('nickname', '姓名', $list['nickname'], '', 'required', 'text',['placeholder' => '必填'])
            ->addSwitch('status', '是否启用', $list['status'])
            ->addSwitch('is_peizi', '是否配资', $list['is_peizi'])
            ->addSwitch('is_del', '是否注销', $list['is_del'])
            ->setUrl(url('editSave'))
            ->setAjax('ajaxForm-noJump')
            ->fetch();
    }

    /**
     * 更新
     */
    public function editSave()
    {
        $id = input('id');
        if (empty($id)) {
            $this->error('参数错误', 'index');
        }

        $data  = [
            'username'       => input('username'),
//            'password'      => input('password'),
            'nickname'         => input('nickname'),
            'status'         => input('status','0'),
            'is_peizi'         => input('is_peizi','0'),
            'is_del'         => input('is_del','0'),
        ];
        if (input('password')!=''){
            $data['password']=encrypt_password(input('password'));
        }

        $rst             = XJihua::update($data);
        if ($rst !== false) {
            $this->success('修改成功', 'index', ['is_frame' => 1]);
        } else {
            $this->error('修改失败', 'index', ['is_frame' => 1]);
        }
    }

    /**
     * 删除
     */
    public function Del()
    {
        $model = new XJihua();
        $rst        = $model->where('id', input('id'))->delete();
        if ($rst !== false) {
            $this->success('删除成功', 'index');
        } else {
            $this->error("删除失败！", 'index');
        }
    }




}